import 'package:flutter/material.dart';
import 'package:shenling/pages/login/index.dart';
import 'package:shenling/pages/message/index.dart';
import 'package:shenling/pages/my/index.dart';
import 'package:shenling/pages/my/setting/index.dart';
import 'package:shenling/pages/task/index.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:shenling/utils/token.dart';

import '../../utils/eventbus.dart';

class TabBarPage extends StatefulWidget {
  const TabBarPage({super.key});

  @override
  State<TabBarPage> createState() => _TabBarPageState();
}

class _TabBarPageState extends State<TabBarPage> {
  bool isLogin = false;
  bool isLoading = true;
  // 记录当前索引
  int currentIndex = 2;

  // 底部TabBar数据
  List tabBarList = [
    {
      "title": "任务",
      "default": "tabs/task_default.svg",
      "active": "tabs/task_default.svg"
    },
    {
      "title": "消息",
      "default": "tabs/message_default.svg",
      "active": "tabs/message_default.svg"
    },
    {
      "title": "我的",
      "default": "tabs/my_default.svg",
      "active": "tabs/my_default.svg"
    }
  ];

  List<BottomNavigationBarItem> barItemList() {
    List<BottomNavigationBarItem> items = [];
    for (var item in tabBarList) {
      items.add(
        BottomNavigationBarItem(
          icon: SvgPicture.asset(
            item['default'],
            width: 32,
            height: 32,
          ),
          activeIcon: SvgPicture.asset(
            colorFilter: const ColorFilter.mode(
              Colors.red, // 目标颜色
              BlendMode.srcIn, // 混合模式
            ),
            item['active'],
            width: 32,
            height: 32,
          ),
          label: item['title'],
        ),
      );
    }
    return items;
  }

  _checkLoginStatus() async {
    // 初始化token管理器
    await TokenManager().init();

    // 检查是否有token
    String? token = TokenManager().getToken();

    setState(() {
      isLogin = token != null && token.isNotEmpty;
      isLoading = false;
    });
  }

  @override
  void initState() {
    super.initState();
    _checkLoginStatus();
    eventBus.on<LogoutEvent>().listen((event) {
      // 跳转登录页面
      Navigator.pushNamed(context, '/login');
    });
  }

  @override
  Widget build(BuildContext context) {
    // 加载过程中显示loading
    if (isLoading) {
      return const Scaffold(
        body: Center(child: CircularProgressIndicator()),
      );
    }

    // 根据登录状态决定显示内容
    if (!isLogin) {
      // 延迟执行跳转，确保context可用
      WidgetsBinding.instance.addPostFrameCallback((_) {
        Navigator.pushReplacementNamed(context, '/login');
      });
      return const Scaffold(
        body: Center(child: CircularProgressIndicator()),
      );
    }
    return Scaffold(
      body: IndexedStack(
        index: currentIndex,
        children: const [TaskPage(), MessagePage(), MyPage()],
      ),
      bottomNavigationBar: BottomNavigationBar(
        type: BottomNavigationBarType.fixed,
        items: barItemList(),
        currentIndex: currentIndex,
        selectedItemColor: const Color.fromARGB(255, 224, 12, 58),
        unselectedItemColor: Colors.black,
        onTap: (index) {
          setState(() {
            currentIndex = index;
          });
        },
      ),
    );
  }
}
